package com.dream.cgomall.service.impl;

import com.dream.cgomall.dao.CgoAdminAddressDao;
import com.dream.cgomall.entity.CgoAdminAddress;
import com.dream.cgomall.service.CgoAdminAddressService;
import com.dream.cgomall.service.ServiceResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * (CgoAdminAddress)表服务实现类
 *
 * @author makejava
 * @since 2021-07-07 15:07:22
 */
@Service
public class CgoAdminAddressServiceImpl implements CgoAdminAddressService {
    @Autowired
    private CgoAdminAddressDao cgoAdminAddressDao;

    @Override
    public ServiceResult updateUserAddress(CgoAdminAddress cgoAdminAddress) {
        try {
            int result = cgoAdminAddressDao.updateAddress(cgoAdminAddress);
            if (result > 0) {
                System.out.println(cgoAdminAddress);
                if (cgoAdminAddress.getIsDefault() == 1) {
                    result = cgoAdminAddressDao.updateother(cgoAdminAddress.getUserId(), cgoAdminAddress.getId());
                    if (result >= 0) {
                        return ServiceResult.success();
                    }
                }
                return ServiceResult.success();
            } else {
                return ServiceResult.badResult("无可修改内容");
            }
        } catch (RuntimeException e) {
            return ServiceResult.badResult("修改内容非法");
        }
    }

    @Override
    public ServiceResult addUserAddress(CgoAdminAddress cgoAdminAddress) {
        try {
            int result = cgoAdminAddressDao.insertAddress(cgoAdminAddress);
            if (result > 0) {
                return ServiceResult.success();
            } else {
                return ServiceResult.badResult("无可修改内容");
            }
        } catch (RuntimeException e) {
            return ServiceResult.badResult("修改内容非法");
        }
    }

    @Override
    public ServiceResult getUserAddress(Integer userId) {
        List<CgoAdminAddress> cgoAdminAddresses = cgoAdminAddressDao.selectAllByUserId(userId);
        return ServiceResult.of(cgoAdminAddresses);
    }

    @Override
    public ServiceResult deleteAddress(Integer id) {
        try {
            int result = cgoAdminAddressDao.deleteById(id);
            if (result > 0) {
                return ServiceResult.success();
            } else {
                return ServiceResult.badResult("删除失败");
            }
        } catch (RuntimeException e) {
            return ServiceResult.badResult("修改内容非法");
        }
    }

    @Override
    public CgoAdminAddress findDefAddress(Integer userId) {
        return cgoAdminAddressDao.findDefaultByUserId(userId);
    }

    @Override
    public CgoAdminAddress findAddressById(Integer addId) {
        return cgoAdminAddressDao.findAddressById(addId);
    }

}
